#include <rtthread.h>
#include "calc.h"
#include "daq.h"
#include "dio_bsp.h"
#include "event_record.h"
#include "i2c_bsp.h"
#include "led_bsp.h"
#include "local_status.h"
#include "req_execution.h"
#include "rtc_bsp.h"
#include "sys_conf.h"
#include "sys_status.h"
#include "watchdog_bsp.h"

static void sys_debug_timeout(void);
static void temp_hum_calc(void);
static void test_mode_init_data(void);

//掉电提示
void power_loss_delay(void)
{
    static uint16_t delay = 0;

    if (delay++ > 30) {
        delay = 11;
        sys_option_di_sts(DI_POWER_LOSS_BPOS, 0);
    }
}

/**
 * @brief 	output control module components cooldown
 * @param  none
 * @retval none
 */
void bkg_thread_entry(void *parameter)
{
    //初始化温湿度曲线记录
    extern sys_reg_st g_sys;
    static uint8_t    u8Num[2] = {0};

    rt_thread_delay(BKG_THREAD_DELAY);
    watchdog_init();

    drv_led_init();
    while (1) {
        led_toggle();
        if (++u8Num[0] >= 2) {
            u8Num[0] = 0;
            temp_hum_calc();
            sys_running_mode_update();
            sys_debug_timeout();
            test_mode_init_data();
            power_loss_delay();

            dog();
        }
        rt_thread_delay(500);
    }
}

static void temp_hum_calc(void)
{
    extern sys_reg_st g_sys;
    g_sys.status.sys_tem_hum.return_air_hum  = get_current_hum(TARGET_MODE_RETURN);
    g_sys.status.sys_tem_hum.return_air_temp = get_current_temp(TARGET_MODE_RETURN);
}

static void test_mode_init_data(void)
{
    extern sys_reg_st   g_sys;
    extern local_reg_st l_sys;

    if (g_sys.config.general.testing_mode_en == TEST_MODE_ENABLE) {  //测试模式
        g_sys.config.dev_mask.din_bitmap_polarity[0] = 0xffff;
        g_sys.config.dev_mask.din_bitmap_polarity[1] = 0xffff;
        g_sys.config.dev_mask.din[0]                 = 0xffff;
        g_sys.config.dev_mask.din[1]                 = 0xffff;
        g_sys.config.dev_mask.mb_comp[COM_TH]        = 3;
        g_sys.config.dev_mask.dout                   = 0xffff;

        l_sys.bitmap[BITMAP_MANUAL] = 0xffff;
    }
}

static void sys_debug_timeout(void)
{
    extern local_reg_st l_sys;
    if (l_sys.debug_tiemout == DEBUG_TIMEOUT_NA) {
        return;
    } else if (l_sys.debug_tiemout > 0) {
        l_sys.debug_tiemout--;
    } else {
        l_sys.debug_flag    = DEBUG_OFF_FLAG;
        l_sys.debug_tiemout = 0;
    }
}
